package com.example.demo;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Color;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Vibrator;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.Toast;

import com.example.demo.Adapter.RegionAdapter;
import com.example.demo.Bean.Region;
import com.getbase.floatingactionbutton.FloatingActionButton;

import java.util.ArrayList;
import java.util.List;

import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.FindListener;
import cn.bmob.v3.listener.SaveListener;

public class MainActivity extends Activity  implements SensorEventListener {

    private String userName = "JX";
    List<Region> list = new ArrayList<Region>();
    private RecyclerView mRecyclerView;
    private RegionAdapter mRegionAdapter;
    private FloatingActionButton regionAdd;
    private FloatingActionButton signOut;
    private SensorManager mSmanager;
    private Vibrator mVibrator;
    private double lastx = 0, lasty = 0, lastz = 0;
    private long last = 0, lastv = 0;
    private int cnt = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        moveStatusbar();
        ininView();
        initData();
        ininOnClick();
    }

    private void moveStatusbar() {
        if(Build.VERSION.SDK_INT >= 21) {
            Window window = getWindow();
            window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS
                    | WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
            window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                    | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                    | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
            window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
            window.setStatusBarColor(Color.TRANSPARENT);
            window.setNavigationBarColor(Color.TRANSPARENT);
        }
    }

    private void ininView() {
        mRecyclerView = (RecyclerView) findViewById(R.id.listview);
        mRecyclerView.setLayoutManager(new LinearLayoutManager(MainActivity.this));
        mRegionAdapter = new RegionAdapter(list,MainActivity.this);
        mRecyclerView.setAdapter(mRegionAdapter);
        mRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                mRegionAdapter.setScrollingMenu(null);
            }
        });
        regionAdd = (FloatingActionButton) findViewById(R.id.region_add);
        signOut = (FloatingActionButton) findViewById(R.id.sign_out);

        mSmanager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
        mVibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);

    }

    private void initData() {
        mSmanager.registerListener(this
                , mSmanager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER)
                ,SensorManager.SENSOR_DELAY_NORMAL);

        if (list != null){
            list.clear();
        }
        BmobQuery<Region> regionBmobQuery = new BmobQuery<>();
        regionBmobQuery.addWhereEqualTo("belong", userName);
        regionBmobQuery.order("-top");
        regionBmobQuery.findObjects(new FindListener<Region>() {
            @Override
            public void done(List<Region> object, BmobException e) {
                if (e == null) {
                    mRegionAdapter.setAdd(object);
                } else {
                    Log.e("BMOB", e.toString());
                }
            }
        });
    }

    private void ininOnClick() {
        regionAdd.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                showInputDialog();
            }
        });

        signOut.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
    }

    public void showInputDialog() {
        EditText editText = new EditText(this);
        AlertDialog.Builder builder = new AlertDialog.Builder(this)
                .setTitle("请输入城市名称")
                .setView(editText)
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        String addName;
                        addName = editText.getText().toString();
                        addName.replace("市", "");
                        Region region = new Region();
                        region.setBelong("JX");
                        region.setName(addName);
                        region.setTop("0");
                        region.save(new SaveListener<String>() {
                            @Override
                            public void done(String s, BmobException e) {
                                if (e == null){
                                    Toast.makeText(MainActivity.this,"保存成功",Toast.LENGTH_SHORT).show();
                                } else {
                                    Toast.makeText(MainActivity.this,"保存失败" + e.getMessage(),Toast.LENGTH_SHORT).show();
                                }
                            }
                        });
                        initData();
                    }
                }).setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                    }
                });
        builder.show();
    }

    @Override
    protected void onResume() {
        super.onResume();
        initData();
    }

    @Override
    protected void onPause() {
        super.onPause();
        mSmanager.unregisterListener(this);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mSmanager.unregisterListener(this);
    }

    @Override
    public void onSensorChanged(SensorEvent sensorEvent) {
        if (sensorEvent.sensor.getType() == Sensor.TYPE_ACCELEROMETER) {
            long now = System.currentTimeMillis();
            if(now - last > 500) {
                double x, y, z;
                x = sensorEvent.values[0];
                y = sensorEvent.values[1];
                z = sensorEvent.values[2];
                if(lastx == 0 && lasty == 0 && lastz == 0) {
                    lastx = x;
                    lasty = y;
                    lastz = z;
                    last = now;
                    return;
                }
                double xx = x - lastx, yy = y - lasty, zz = z - lastz;
                double speed = Math.sqrt(xx*xx + yy*yy + zz*zz);
                if(speed > 15) {
                    cnt++;
                    if(cnt % 3 == 0) {
                        long nn = System.currentTimeMillis();
                        if(nn - lastv >= 10000) {
                            mVibrator.vibrate(500);
                            showInputDialog();
                            lastv = nn;
                        }
                    }
                }
            }
        }
    }

    @Override
    public void onAccuracyChanged(Sensor sensor, int i) {
    }

}